<!--
 * @Description: 窗帘到货单
 *
 * @Author: guichengcai<guichengcai>
 * @Date: 2023-06-29 17:11:54
 * @FilePath: /yuxiuproweb/src/views/buys/clbuyarrival/index.vue
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      class="queryForm"
    >
      <el-form-item label="到货单号" prop="arrivalNoteNumber">
        <el-input
          v-model="queryParams.arrivalNoteNumber"
          placeholder="请输入到货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="到货明细" prop="arrivalNoteItemId">
        <el-input
          v-model="queryParams.arrivalNoteItemId"
          placeholder="请输入到货明细"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-select
          v-model="queryParams.supplier"
          placeholder="请选择供应商名称"
          style="width: 100%"
          clearable
          filterable
          remote
          reserve-keyword
          :remote-method="getSupplierData"
          @change="handleQuery"
        >
          <el-option
            v-for="item in supplierData"
            :key="item.vendorId"
            :label="item.vendorName"
            :value="item.vendorName"
          >
            <span style="padding-left: 6px">{{ item.vendorName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="型号" prop="modelNumber">
        <el-input
          v-model="queryParams.modelNumber"
          placeholder="请输入型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select
          style="width: 100%"
          v-model="queryParams.state"
          placeholder="请选择状态"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option :label="'待验'" value="0"></el-option>
          <el-option :label="'入库'" value="1"></el-option>
          <el-option :label="'退货'" value="2"></el-option>
          <el-option :label="'协商'" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="createDate">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="queryParams.createDateObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增到货单</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handleputIsUrgent"
          >加急验布</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="recordList"
      @selection-change="handleSelectionChange"
      :max-height="maxHeight"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '4px 0' }"
      border
    >
      <el-table-column type="selection" width="55" align="center" fixed />
      <template v-for="(i, index) in tableForm.item">
        <el-table-column
          :key="index"
          :prop="i.itemcode"
          :columnKey="i.itemcode"
          :label="i.itemname"
          :align="i.aligntype ? i.aligntype : 'center'"
          :min-width="i.minwidth"
          :width="!!i.width ? i.width : ''"
          :show-overflow-tooltip="i.overflow ? true : false"
          :sortable="i.sortable ? true : false"
          v-if="i.displaymark ? true : false"
          :fixed="i.fixed"
        >
          <template slot-scope="scope">
            <el-button
              v-if="i.itemcode == 'arrivalNoteItemId'"
              type="text"
              @click="handlechange(scope.row)"
              >{{ scope.row[i.itemcode] }}</el-button
            >
            <div v-else-if="i.itemcode == 'state'">
              <span v-if="scope.row[i.itemcode] == 0">待验</span>
              <span v-if="scope.row[i.itemcode] == 1">入库</span>
              <span v-if="scope.row[i.itemcode] == 2">退货</span>
              <span v-if="scope.row[i.itemcode] == 3">协商</span>
            </div>
            <div v-else-if="i.itemcode == 'qualityStatus'">
              <span v-if="scope.row[i.itemcode] == 1">合格</span>
              <span v-if="scope.row[i.itemcode] == 0">不合格</span>
            </div>
            <div v-else-if="i.itemcode == 'createTime'">
              <span>{{ scope.row[i.itemcode] | dateFormat }}</span>
            </div>
            <span v-else>{{ scope.row[i.itemcode] }}</span>
          </template>
        </el-table-column>
      </template>
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="120px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlechange(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handledelete(scope.row)"
            style="color: #ff4949"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openkc"
      width="78vw"
      append-to-body
    >
      <el-form ref="formaddkc" label-width="100px">
        <div style="display: flex; align-items: center;margin-bottom: 15px;">
          <el-select
            v-model="addParams.supplier"
            placeholder="请选择供应商"
            style="width: 200px; margin-right: 10px"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="getSupplierData"
            @change="getqbOrder"
            @clear="getqbOrder"
          >
            <el-option
              v-for="item in supplierData"
              :key="item.vendorId"
              :label="item.vendorName"
              :value="item.vendorName"
            >
              <span style="padding-left: 6px">{{ item.vendorName }}</span>
            </el-option>
          </el-select>
          <el-input
            placeholder="请输入型号"
            v-model="addParams.modelNumber"
            style="width: 200px;margin-right: 10px"
            clearable
            @keyup.enter.native="getqbOrder()"
          >
          </el-input>
		  <el-input
		    placeholder="请输入供应商型号"
		    v-model="addParams.vendorModel"
		    style="width: 200px;margin-left: 10px;"
		    size="small"
		    clearable
		    @keyup.enter.native="search()"
		  >
		  </el-input>
          <el-button
            class="filter-item"
            type="primary"
            size="small"
            @click="getqbOrder()"
          >
            查询
          </el-button>
        </div>
        <el-table
          v-loading="loading"
          :data="applylist"
          @selection-change="handleSelectionChanges"
          :max-height="maxHeight"
          border
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="采购ID"
            prop="purchaseOrderId"
            align="center"
            width="80px"
          />
          <el-table-column
            label="采购单号"
            prop="orderNumber"
            align="center"
            width="120px"
          />
          <el-table-column
            label="供应商"
            width="100"
            prop="supplier"
            align="center"
          />
          <el-table-column
            label="存货编码"
            width="100"
            prop="codeNumber"
            align="center"
          />
          <el-table-column
            label="型号"
            width="100"
            prop="modelNumber"
            align="center"
          />
		  <el-table-column
		    label="供应商型号"
		    width="100"
		    prop="vendorModel"
		    align="center"
		  />
          <el-table-column
            label="门幅"
            width="80"
            prop="fabricWidth"
            align="center"
          />
          <el-table-column
            label="申请量"
            width="120"
            prop="quantity"
            align="center"
          />

          <el-table-column
            label="到货量"
            width="120"
            prop="inventoryQuantityStr"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'applylist.' + scope.$index + '.inventoryQuantityStr'"
              >
                <el-input v-model="scope.row.inventoryQuantityStr"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="备注"
            prop="itemRemark"
            :show-overflow-tooltip="true"
          /> -->
          <el-table-column label="备注" prop="itemRemark" min-width="150">
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordListkc.' + scope.$index + '.itemRemark'"
              >
                <el-input
                  v-model="scope.row.itemRemark"
                  placeholder="备注"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="addParams.pageNum"
          :limit.sync="addParams.pageSize"
          @pagination="getqbOrder"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormadd">确 定</el-button>
        <el-button @click="openkc = false">取 消</el-button>
      </div>
    </el-dialog>
    <detail-view
      v-if="detailopen.show"
      :show.sync="detailopen.show"
      v-bind="detailopen"
      @update="getList"
    ></detail-view>
  </div>
</template>

<script>
import {
  listRecords,
  addarrival,
  putIsUrgent,
  deleteItem,
} from "@/api/buys/clbuyarrival";
import { listRecord } from "@/api/buys/qbbuyapply";
import commonMix from "@/utils/mixins/common";
import { tableList } from "./mods/tablecolums.js";
import { listVendor } from "@/api/mes/md/vendor";
import DetailView from "./mods/detail.vue";
export default {
  mixins: [commonMix],
  components: { DetailView },
  name: "Record",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      selRow: [],
      selRow: [],
      openkc: false,
      // 交易记录表格数据
      recordList: [],
      applylist: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        orderId: null,
        clientId: null,
        clientName: null,
        cashAccount: null,
        rebateAccount: null,
        otherAccount: null,
      },
      addParams: {
        pageNum: 1,
        pageSize: 100,
        modelNumber: null,
        supplier: null,
        supplierId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      tableForm: tableList,
      supplierData: [],
      detailopen: {
        show: false,
        data: null,
      },
    };
  },
  created() {
    this.getList();
    this.getSupplierData();
  },
  methods: {
    submitFormadd() {
      if (this.selRow.length > 0) {
        const paramskc = {
          items: this.selRow,
          subscriptionType: 1, //类型:窗帘
        };
        console.log(paramskc);
        addarrival(paramskc).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.openkc = false;
          this.getList();
        });
      } else {
        this.$message.error("请勾选申购单");
      }
    },
    /** 查询交易记录列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        startDate: this.queryParams.createDateObj?.[0] || null,
        endDate: this.queryParams.createDateObj?.[1] || null,
        subscriptionType: 1,
      };
      delete params.createDateObj;
      listRecords(params).then((response) => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleSelectionChanges(val) {
      this.selRow = [];
      this.selRow = val;
      // 获取表单所有要校验的字段
      this.verify = [];
      // 将选中的数据和全部表格中校验的字段遍历 取出勾选对应的校验字段、并将没勾选的校验去除
      let vsl = {};
      val.forEach((element) => {
        vsl = {
          codeNumber: element.codeNumber,
          quantity: element.quantity,
          fabricWidth: element.fabricWidth,
          modelNumber: element.modelNumber,
          inventoryQuantityStr: element.inventoryQuantityStr,
        };
        this.verify.push(vsl);
      });
      // scope.$index当前行数据在数组中的索引，勾选哪一行校验哪一行的必填项
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.transactionRecordId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.selRow = selection;
    },

    handleAdd() {
      this.openkc = true;
      this.title = "新增到货单";
      this.getqbOrder();
    },
    getqbOrder() {
      const params = {
        ...this.addParams,
        type: 1,
        itemStatus: 3,
      };
      listRecord(params).then((response) => {
        this.applylist = response.rows;
      });
    },
    // 加急验布
    async handleputIsUrgent() {
      if (!this.selRow.length) {
        this.$message.error("请勾选单据");
        return;
      }
      let promiseList = [];
      for (var i = 0; i < this.selRow.length; i++) {
        var item = this.selRow[i];
        var that = this;
        let promise = new Promise((resolve, reject) => {
          if (item.isUrgent == "加急") {
            item.isUrgent = "";
          } else {
            item.isUrgent = "加急";
          }
          putIsUrgent(item)
            .then((res) => {
              resolve(res || "操作成功");
            })
            .catch((er) => {
              // reject("操作失败");
            });
        });
        promiseList.push(promise);
      }
      await Promise.all(promiseList)
        .then((res) => {
          this.$modal.msgSuccess(res.msg || "操作成功");
        })
        .catch((er) => {})
        .finally(() => {
          this.getList();
        });
    },
    getSupplierData(vendorName = "") {
      listVendor({
        pageNum: 1,
        pageSize: 100,
        vendorName,
      }).then(({ rows }) => {
        this.supplierData = rows;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "statistic/export",
        {
          ...this.queryParams,
        },
        `record_${new Date().getTime()}.xlsx`
      );
    },
    getSpanArr(list, code, rowSpan) {
      let arrZero = [];
      return list.map((item, i) => {
        let RowSpanNum = 1;
        for (let j = i + 1; j < list.length; j++) {
          if (item[code] === list[j][code]) {
            arrZero.push(j);
            RowSpanNum++;
          } else {
            break;
          }
        }
        if (arrZero.findIndex((ele) => ele == i) != -1) {
          RowSpanNum = 0;
        }
        return {
          ...item,
          [rowSpan]: RowSpanNum,
        };
      });
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (column.columnKey == "arrivalNoteNumber") {
        return {
          rowspan: row.dealRowSpan,
          colspan: 1,
        };
      }
    },
    handledelete(row) {
      if (row.state != 0) {
        this.$message.error("当前状态下不可删除！");
        return;
      }
      var that = this;
      this.$confirm("是否确认删除，此操作不可逆, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteItem(row.arrivalNoteItemId).then((res) => {
          this.$modal.msgSuccess(res.msg || "删除成功");
          this.getList();
        });
      });
    },
    handlechange(row) {
      const datarow = { ...row } || null;
      this.detailopen = {
        show: true,
        data: datarow,
      };
    },
  },
  filters: {
    dateFormat(dataStr) {
      if (!dataStr) {
        return;
      }
      var dt = new Date(dataStr);
      var y = dt.getFullYear();
      var m = (dt.getMonth() + 1).toString().padStart(2, "0");
      var d = dt.getDate().toString().padStart(2, "0");
      var hh = dt.getHours().toString().padStart(2, "0");
      var mm = dt.getMinutes().toString().padStart(2, "0");
      var ss = dt.getSeconds().toString().padStart(2, "0");
      //
      return `${y}-${m}-${d}`;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .el-form-item__content {
    margin-left: 0px !important;
  }
  .el-form-item {
    margin-bottom: 0 !important;
  }
  .queryForm .el-form-item {
    margin-bottom: 20px !important;
  }
}
</style>
